<!--
 * @Description: 角色管理-新建角色
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2024-03-05
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-09-24
-->
<script lang="ts" setup>
  import { Form, message } from 'ant-design-vue'
  import { computed, reactive, watch } from 'vue'

  import { requestSaveRole } from '/@/api/system/ysys-user/role'
  import { RoleTypeDesc } from '/@/api/system/ysys-user/role/enum'
  import { HttpCodeEnum } from '/@/enums/httpEnum'

  const props = defineProps({
    visible: { type: Boolean, default: false },
  })

  const emits = defineEmits(['update:visible', 'success'])

  const visible = computed({
    get: () => props.visible,
    set: (val) => emits('update:visible', val),
  })

  watch(
    () => visible.value,
    (newVal) => {
      if (newVal) onPageshow()
      else onPageHide()
    },
  )

  /**
   * 页面显示
   */
  const onPageshow = () => {}

  /**
   * 页面关闭
   */
  const onPageHide = () => resetFields()

  /** 表单配置 */
  const form = reactive({
    state: {
      roleName: '',
      roleType: null,
      roleDesc: '',
    },
    rule: {
      roleName: [{ required: true, message: '请输入角色名称' }],
      roleType: [{ required: true, message: '请选择类型' }],
    },
    options: {
      roleType: Object.entries(RoleTypeDesc).map((item) => ({ label: item[1], value: parseInt(item[0]) })),
    },
    onOk: () => {
      validate()
        .then(async () => {
          const { roleName, roleType, roleDesc } = form.state
          const { responseCode } = await requestSaveRole({ roleName, roleType, roleDesc })
          if (responseCode === HttpCodeEnum.SUCCESS) {
            message.success('添加成功')
            visible.value = false
            emits('success')
          }
        })
        .catch(() => {})
    },
  })
  /** 表单hook */
  const { validate, validateInfos, resetFields } = Form.useForm(form.state, form.rule)
</script>

<template>
  <div class="add">
    <a-modal v-model:visible="visible" title="新建角色" @ok="form.onOk">
      <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="角色名称" v-bind="validateInfos.roleName">
          <a-input v-model:value="form.state.roleName" />
        </a-form-item>
        <a-form-item label="类型" v-bind="validateInfos.roleType">
          <a-select v-model:value="form.state.roleType" :options="form.options.roleType" placeholder="请选择" />
        </a-form-item>
        <a-form-item label="角色描述" v-bind="validateInfos.roleDesc">
          <a-input v-model:value="form.state.roleDesc" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style lang="less" scoped></style>
